
#define DBG_TAG "MAIN"
#include "log.h"
#include "si4432.h"
#include "sv17f_uart.h"
#include "bflb_wdg.h"
#include <FreeRTOS.h>
#include <queue.h>
#include <task.h>

struct bflb_device_s *wdg;
struct bflb_device_s *gpioStatus;

void wdg_task(void *arg)
{
    bflb_mtimer_delay_ms(2000);
    struct bflb_wdg_config_s wdg_cfg;
    wdg_cfg.clock_source = WDG_CLKSRC_32K;
    wdg_cfg.clock_div = 31;
    wdg_cfg.comp_val = 2000;
    wdg_cfg.mode = WDG_MODE_RESET;

    wdg = bflb_device_get_by_name("watchdog");
    bflb_wdg_init(wdg, &wdg_cfg);

    bflb_wdg_start(wdg);
    bflb_wdg_reset_countervalue(wdg);

    while (1) {
        bflb_mtimer_delay_ms(1000);
        if (get_ver() == 0x06) {
            bflb_wdg_reset_countervalue(wdg);
            printf("延迟. \r\n");
            if(bflb_gpio_read(gpioStatus, GPIO_PIN_12)){
                bflb_gpio_reset(gpioStatus, GPIO_PIN_12);
            }
        } else {
            if(!bflb_gpio_read(gpioStatus, GPIO_PIN_12)){
                bflb_gpio_set(gpioStatus, GPIO_PIN_12);
            }
            printf("SI4432没初始化成功. \r\n");
        }
        // value = bflb_wdg_get_countervalue(wdg);
        // printf("延迟. %d\r\n", value);
    }
}


/**
 * @brief 按钮点击检测，停止播放声音
 * 
 * @param arg 
 */
void button_check(void *arg)
{
    struct bflb_device_s *gpio = bflb_device_get_by_name("gpio");
    bflb_gpio_init(gpio, GPIO_PIN_33, GPIO_INPUT | GPIO_PULLUP | GPIO_SMT_EN | GPIO_DRV_0);
    bflb_gpio_set(gpio, GPIO_PIN_33);

    gpioStatus = bflb_device_get_by_name("gpio");
    bflb_gpio_init(gpioStatus, GPIO_PIN_12, GPIO_INPUT | GPIO_PULLUP |GPIO_DRV_0);
    
    LOG_E("button_check \r\n");
    while (1) {
        if (bflb_gpio_read(gpio, GPIO_PIN_33) == 0) {
            LOG_E("按钮被按下 \r\n");
            while (bflb_gpio_read(gpio, GPIO_PIN_33) == 0) {
                bflb_mtimer_delay_ms(10);
            }
            LOG_E("按钮被抬起 \r\n");
            sv17f_stop();
        }
        bflb_mtimer_delay_ms(100);
    }
}

int main(void)
{
    board_init();
   
    LOG_E("RF_DEVICE_ID: 0x%02x \r\n", RF_DEVICE_ID);
    xTaskCreate(si4432_task, "si4432_task", 1024, NULL, 2, NULL);
    xTaskCreate(sv17f_uart_task, "sv17f_uart_task", 1024, NULL, 3, NULL);
    xTaskCreate(button_check, "button_check", 1024, NULL, 2, NULL);
    xTaskCreate(wdg_task, "wdg_task", 1024, NULL, 2, NULL);
    vTaskStartScheduler();
}
